package com.zy.pool.factory;

import com.zy.pool.domain.DBbean;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.Synchronized;
import lombok.extern.java.Log;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

@Log
public class ConnectionFactory {

    @NonNull
    @Getter
    @Setter
    private DBbean dBbean;

    private ConnectionFactory(Builder builder) {
        dBbean = builder.dBbean;
        init();
    }

    private void init(){
        if(dBbean!=null){
            try {
                Class.forName(dBbean.getDriverName());
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    @Synchronized
    public Connection getConnection(){
        Connection connection =null;
        try {
            connection = DriverManager.getConnection(dBbean.getUrl(), dBbean.getUserName(), dBbean.getPassword());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }



    public static final class Builder {
        private DBbean dBbean;

        public Builder() {
        }

        public Builder dBbean(DBbean val) {
            dBbean = val;
            return this;
        }

        public ConnectionFactory build() {
            return new ConnectionFactory(this);
        }
    }
}
